package com.wxit.algorithm.leetcode;

/**
 * 删除有序链表重复节点
 */
public class E05LeetCode82 {

    /**
     * 三个指针方法
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode s = new ListNode(-1, head);
        ListNode p1 = s;
        ListNode p2, p3;
        while ((p2 = p1.next) != null && (p3 = p2.next) != null) {
            if (p2.val == p3.val) {
                while ((p3 = p3.next) != null && p3.val == p2.val) {

                }
                //p3找不到和p2相同的节点
                p1.next = p3;
            } else {
                p1 = p1.next;
            }
        }
        return s.next;
    }



    /**
     * 递归实现法
     * @param p
     * @return
     */
    public ListNode deleteDuplicates01(ListNode p) {
        //边界条件, 为空或者只有一个节点
        if (p == null || p.next == null) {
            return p;
        }
        if (p.val == p.next.val) {
            ListNode x = p.next.next;
            while (x != null && x.val == p.val) {
                x = x.next;
            }
            //返回与 p 取值不同的节点
            return deleteDuplicates01(x);
        } else {
            p.next = deleteDuplicates01(p.next);
            return p;
        }
    }

    public static void main(String[] args) {
        ListNode head = ListNode.of(1, 2, 3, 3, 4, 4, 5);
        System.out.println(head);
        System.out.println(new E05LeetCode82().deleteDuplicates(head));
    }
}
